<?php
/**
 * Object Relational Persistence Mapping Class for table: medical_record
 *
 * @package	com.clearhealth
 * @author	ClearHealth Inc.
 */
class MedicalRecord extends ORDataObject {

	/**#@+
	 * Fields of table: medical_record mapped to class members
	 */
	var $medical_record_id		= '';
	var $ticket_id		= '';
	var $patient_id		= '';
	var $date		= '';
	var $status		= '';
	/**#@-*/


	/**
	 * DB Table
	 */
	var $_table = 'medical_record';

	/**
	 * Primary Key
	 */
	var $_key = 'medical_record_id';
	
	/**
	 * Internal Name
	 */
	var $_internalName = 'MedicalRecord';
	
	const OPEN_STATUS = "open";
	const CLOSED_STATUS = "closed";

	/**
	 * Handle instantiation
	 */
	function MedicalRecord() {
		parent::ORDataObject();
	}

	
	/**#@+
	 * Field: date, time formatting
	 */
	function get_date() {
		return $this->_getDate('date');
	}
	function set_date($date) {
		$this->_setDate('date',$date);
	}
	/**#@-*/
	
	function setup($mrId = 0) {
		if ($mrId > 0) {
			$this->set('medical_record_id', $mrId);
			$this->populate();
		}
	}
	
	public function closeTicket($ticketId) {
	    $sql = "update medical_record set status='" . MedicalRecord::CLOSED_STATUS . "' where ticket_id = $ticketId";
		$this->_execute($sql);
	}
	
	public function delete($medicalRecordId) {
		// Delete document_store
		$sql = "SELECT document_store_id FROM document_store WHERE medical_record_id=$medicalRecordId";
		$res = $this->_execute($sql);
		if ($res && !$res->EOF) {
			Celini::newORDO('DocumentStore')->delete($res->fields['document_store_id']);
		}
		
		// Delete laboratory
		$sql = "SELECT laboratory_id FROM laboratory WHERE medical_record_id=$medicalRecordId";
		$res = $this->_execute($sql);
		if ($res && !$res->EOF) {
			Celini::newORDO('Laboratory')->delete($res->fields['laboratory_id']);
		}
		
		// Delete prescription
		$sql = "SELECT prescription_id FROM prescription WHERE medical_record_id=$medicalRecordId";
		$res = $this->_execute($sql);
		if ($res && !$res->EOF) {
			Celini::newORDO('Prescription')->delete($res->fields['prescription_id']);
		}
		
		// Delete surgery
		$sql = "SELECT surgery_id FROM surgery WHERE medical_record_id=$medicalRecordId";
		$res = $this->_execute($sql);
		if ($res && !$res->EOF) {
			Celini::newORDO('Surgery')->delete($res->fields['surgery_id']);
		}
		
		// Delete medical_record
		$sql = "DELETE FROM medical_record WHERE medical_record_id=$medicalRecordId";
		$this->_execute($sql);
	}
	
	public function getAllRecordOfPatient($patientId, $open) {
	    // In this version of Athena, the medical record is no longer in CLOSED status
	    // So, always display as OPEN
	    $status = MedicalRecord::OPEN_STATUS;
		/*$status = MedicalRecord::CLOSED_STATUS;
		if ($open) {
			$status = MedicalRecord::OPEN_STATUS;
		}*/
		$ds = new Datasource_sql();
		$sql = array(
			'cols' 		=> "medical_record_id, patient_id, date, status",
			'from' 		=> "$this->_table",
			'where' 	=> "patient_id = $patientId AND status='" . $status ."'",
			'orderby' 	=> 'date DESC'
			);
					
		$ds->setup($this->_db,$sql);
		return $ds->toArray();
	}
	
	public function getAllRecordOfPatientByDepartment($patientId, $departmentId, $open) {
		$status = MedicalRecord::CLOSED_STATUS;
		if ($open) {
			$status = MedicalRecord::OPEN_STATUS;
		}
		$ds = new Datasource_sql();
		$sql = array(
			'cols' 		=> "emr.medical_record_id, emr.patient_id, emr.date, emr.status",
			'from' 		=> "$this->_table emr
				INNER JOIN ticket t on emr.ticket_id = t.ticket_id",
			'where' 	=> "emr.patient_id = $patientId
					AND t.department_id = $departmentId
					AND emr.status='" . $status ."'",
			'orderby' 	=> 'emr.date DESC'
			);
					
		$ds->setup($this->_db,$sql);
		return $ds->toArray();
	}
	
    
	public function getTreatmentHistory($patientId) {
        $ds = new Datasource_sql();
        $sql = array(
            'cols'      => "mr.ticket_id, mr.medical_record_id, mr.date AS iso_date,
                            ge.primary_icd10",
            'from'      => "$this->_table mr
                                LEFT JOIN emr_general_examination ge ON mr.medical_record_id = ge.medical_record_id",
            'where'     => "mr.patient_id = $patientId",
            'orderby'   => 'mr.date',
            'limit'     => 10
            );
                    
        $ds->setup($this->_db,$sql);
        return $ds->toArray();
    }

	function getMedicalRecord($recordId){
		$ds = new Datasource_sql();
		$sql = array(
			'cols' 		=> "medical_record_id, patient_id, date, status",
			'from' 		=> "$this->_table",
			'where' 	=> "medical_record_id = $recordId"
			);
					
		$ds->setup($this->_db,$sql);
		return $ds->toArray();
	}
	
	public function isAnyOpenRecord($ticketId) {
		$status = MedicalRecord::OPEN_STATUS;
		$sql = "SELECT medical_record_id
				FROM $this->_table
				WHERE ticket_id = '$ticketId' AND status = '$status'";
		$res = $this->_execute($sql);
		if ($res && !$res->EOF) {
			return $res->fields['medical_record_id'];
		}
		return false;
	}
	
	public function getRecordIdFromTicket($ticketId) {
		$status = MedicalRecord::OPEN_STATUS;
		$sql = "SELECT medical_record_id FROM $this->_table WHERE ticket_id = '$ticketId'";
		$res = $this->_execute($sql);
		if ($res && !$res->EOF) {
			return $res->fields['medical_record_id'];
		}
		return false;
	}
	
	public function addNewRecord($patientId, $ticketId) {
		$data = array (	'patient_id' => $patientId,
						'ticket_id'  => $ticketId,
						'date'       => date('Y-m-d'),
						'status'     => MedicalRecord::OPEN_STATUS );
		$this->populateArray($data);
		$this->persist();
		return $this->get_id();
	}
	
	public function getTicketId() {
		return $this->ticket_id;
	}

}
?>
